package com.keshihao.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.keshihao.eduservice.entity.EduChapter;
import com.keshihao.eduservice.entity.EduVideo;
import com.keshihao.eduservice.entity.chapter.ChapterVo;
import com.keshihao.eduservice.entity.chapter.VideoVo;
import com.keshihao.eduservice.mapper.EduChapterMapper;
import com.keshihao.eduservice.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.keshihao.eduservice.service.EduVideoService;
import com.keshihao.servicebase.exceptionhandler.TechException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author keshihao
 * @since 2020-05-25
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {

    @Autowired
    private EduVideoService eduVideoService;

    // 课程大纲列表,根据课程id进行查询
    @Override
    public List<ChapterVo> getChapterVideoByCourseId(String courseId) {

        // 1.根据课程id查询课程里面所有的章节
        List<EduChapter> eduChapterList = baseMapper.selectList(new QueryWrapper<EduChapter>().eq("course_id", courseId));


        // 2.根据课程id查询课程里面所有的小节
        List<EduVideo> eduVideoList = eduVideoService.list(new QueryWrapper<EduVideo>().eq("course_id", courseId));

        // 创建list集合，用于最终封装数据
        List<ChapterVo> finalList = new ArrayList<>();

        // 3.遍历查询章节list集合进行封装
        for (EduChapter eduChapter : eduChapterList) {
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(eduChapter,chapterVo);
            finalList.add(chapterVo);
        }

        // 4.遍历查询小节list集合，进行封装
        for (ChapterVo chapterVo : finalList) {
            List<VideoVo> videoVoList = new ArrayList<>();
            for (EduVideo eduVideo : eduVideoList) {
                if (eduVideo.getChapterId().equals(chapterVo.getId())) {
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(eduVideo,videoVo);
                    videoVoList.add(videoVo);
                }
            }
            chapterVo.setChildren(videoVoList);
        }


        return finalList;
    }

  @Override
  public Boolean deleteChapter(String chapterId) {
    int count = eduVideoService.count(new QueryWrapper<EduVideo>().eq("chapter_id", chapterId));

    if (count > 0) { // 查询出有小节数据，不能进行删除
      throw new TechException(20001,"不能删除");
    } else { // 不能查询出小节数据，进行删除
      // 删除章节
      int result = baseMapper.deleteById(chapterId);
      return result > 0;
    }


  }

    @Override
    public void removeChapterByCourseId(String courseId) {
        baseMapper.delete(new QueryWrapper<EduChapter>().eq("course_id",courseId));
    }

}
